<template>
	<view>
		<cu-custom :bgColor="globalColor" :isBack="true">
		    <block slot="content">视频解析</block>
		</cu-custom>
		<ad v-if="showAd" :unit-id="ad" ad-type="video" ad-theme="white"></ad>
		<view>
			<video class="video-play" :poster="cover" v-bind:src="videoUrl"/>
		</view>
		<cmd-progress :percent="percent" :success-percent="percent" stroke-color="white" custom>
		  <text style="color: #009688;">{{percent}}%</text>
		</cmd-progress>
		<view class="box">
			<view class="cu-bar btn-group">
				<button class="cu-btn bg-orange shadow-blur" @click="copyMvUrl">复制无水印链接</button>
				<button class="cu-btn bg-green  shadow" @click="downFile(1,videoUrl)">保存到手机</button>
			</view>
		</view>
		<view class="box" v-if="null != cover">
			<view class="cu-bar btn-group">
				<button class="cu-btn bg-blue shadow-blur" v-if="null != cover" @click="copyCover()">复制封面链接</button>
				<button class="cu-btn bg-grey  shadow" v-if="null != cover" @click="downFile(2,cover)">保存封面</button>
			</view>
		</view>
		<view class="padding-sm flex flex-direction" style="margin-top: -7px;" @click="skipToPrize()">
			<button class="cu-btn bg-cyan">{{prizeContent}}</button>
		</view>
		<view class="padding-sm flex flex-direction" style="margin-top: -7px;" @click="back()">
			<button class="cu-btn" style="margin-left: 2px;background: #16A7F8;color: white;">返回首页继续解析</button>
		</view>
		<view class="padding-sm flex flex-direction" style="margin-top: -7px;">
			<button class="cu-btn" style="margin-left: 2px;background: #16A7C4;color: white;">在线客服</button>
		</view>
		<view class="water-teach">
			<view class="tui-nickname" @click="skipToWeb">
				<image src="../../static/teach.png" class="tui-img-vip"></image>下载失败了怎么办？ 点我查看解决方式
			</view>
		</view>
		<ad v-if="showAd" :unit-id="indexAd" ad-type="video" ad-theme="white"></ad>
		<!-- #ifdef MP-WEIXIN -->
		<privacy-popup></privacy-popup>
		<!-- #endif -->
		
	</view>

</template>

<script>
	import cmdProgress from "@/components/cmd-progress/cmd-progress.vue"
	export default {
		components: {
			cmdProgress
		},
		data() {
			return {
				videoUrl:getApp().globalData.playAddr,
				percent:0,
				fileStatus:'success',
				rewardedVideoAd:null,
				videoType:0,
				prizeContent:getApp().globalData.prizeContent,
				rewardedVideoAd:null,
				author:getApp().globalData.author,
				cover:getApp().globalData.cover,
				title:null,
				currentTimeStamp:null,
				showAd:false,
				ad:'',
				videoAfterAd:'',
				downLoadType:1,
				adError:0,
				globalColor: getApp().globalData.globalColor
			}
		},
		onLoad(options) {
			this.ad = getApp().globalData.videoAd
			this.showAd = true
			this.createRewardCard()
			this.createRewardVideo()
			this.percent = 0;
			var autoDownFile = getApp().globalData.autoDownload
			if(null != options.type) {
				this.videoType = options.type;
			}
			if(null != autoDownFile && autoDownFile == true) {
				this.downFile(1,this.videoUrl);
			}
			
		},
		onShareAppMessage(res) {
			return {
			  title: getApp().globalData.shareTitle,
			  path: '/pages/index/index',
			  imageUrl: getApp().globalData.sharePic
			}
		},
		methods: {
			back() {
				uni.switchTab({
					url:'../index/index'
				})
			},
			createRewardVideo() {
				var that = this;
				try{
					this.rewardedVideoAd = wx.createRewardedVideoAd({adUnitId: getApp().globalData.videoAdReward})
					this.rewardedVideoAd.onError(err => {
						console.log("============================="+err)
					  that.adError = 1
					})
					
					//监听广告是否看完
					that.rewardedVideoAd.onClose(res => {							
						if (res && res.isEnded) {
							console.log("===========广告看完了===========")
							uni.request({
								url:that.$reqUrl + "/lyz/updateUserAdTimes?uid="+getApp().globalData.uid,
								method:'get',
								success: (res) => {
									console.log(res.data)
								}
							})
						    that.startDownLoad(that.downLoadType,that.videoUrl)
						} else {
						  uni.showModal({
							content:getApp().globalData.adTip
						  })
						}
					})  
				}catch(e){
					console.log("========ssssssss====================="+err)
					that.adError = 1
					that.startDownLoad(that.downLoadType,that.videoUrl)
					console.log(e)
				}		
			},
			createRewardCard() {
				let interstitialAd = null
				if(wx.createInterstitialAd){
				      interstitialAd = wx.createInterstitialAd({ adUnitId: getApp().globalData.videoAdCard})
				      interstitialAd.onLoad(() => {
				        console.log('onLoad event emit')
				      })
				      interstitialAd.onError((err) => {
				        console.log('onError event emit', err)
				      })
				      interstitialAd.onClose((res) => {
				        console.log('onClose event emit', res)
				      })
					  
					  var random = Math.floor(Math.random()*10); 
					  if(random == 4 || random == 8) {
						  interstitialAd.show().catch((err) => {
						    console.error(err)
						  })
					  } 
				}
			},
			copyCover() {
				uni.setClipboardData({
					data: getApp().globalData.cover,
					success: function () {
						uni.showModal({
							content:'已经复制链接到剪切板,请粘贴到浏览器下载'
						})
					}
				});
			},
			copyMvUrl() {
				var that = this;
				uni.setClipboardData({
					data: that.videoUrl,
					success: function () {
						uni.setStorageSync(that.videoUrl,that.videoUrl)
						uni.showModal({
							content:'已经复制无水印链接到剪切板,请粘贴到浏览器下载'
						})
					}
				});
			},
			skipToPrize:function (){
				var that = this;
				if(getApp().globalData.prizeType == 1) {
					uni.previewImage({
						urls: [getApp().globalData.prizeImg],
						longPressActions: {
							itemList: ['发送给朋友', '保存图片', '收藏']
						}
					});
				}else {
					uni.navigateToMiniProgram({
					  appId: 'wx18a2ac992306a5a4',
					  path:getApp().globalData.prizePath		  
					})
				}
			},
			skipToWeb:function(type) {
				uni.navigateTo({
					url:'../parse/parse?conId=27'
				})
			},
			downFile(type,fileUrl) {
				var that = this;
				that.downLoadType = type
				var timestamp = (new Date()).valueOf();
				console.log(timestamp)
				if(that.currentTimeStamp == null) {
					that.currentTimeStamp = timestamp;
				}else {
					if(timestamp - that.currentTimeStamp < 5000) {
						uni.showModal({
							content:'下载频率过快，请两秒后重新下载'
						})
						return
					}else {
						that.currentTimeStamp = timestamp;
					}
				}
				if(that.videoType == 1 && type == 1) {
					uni.showModal({
						content:'该视频超过50M,请复制视频链接到浏览器下载'
					})
					return
				}
				
				
				uni.showLoading({
					title:'初始化资源'
				})
				
				
				uni.request({
					url:that.$reqUrl + "/lyz/getUserAdTimes?uid="+getApp().globalData.uid,
					method:'get',
					success(res) {
						if(res.data.data < getApp().globalData.watchTimes && that.adError == 0) {
							try{
								that.rewardedVideoAd.show().catch(() => {
									that.rewardedVideoAd.load()
									  .then(() => that.rewardedVideoAd.show())
									  .catch(err => {that.startDownLoad(type,fileUrl)})
								  })
							}catch(e) {
								that.startDownLoad(type,fileUrl)
							}
				
						}else {
							that.startDownLoad(type,fileUrl)
						}
					},complete(res) {
						uni.hideLoading()
					}
				})
			},
			startDownLoad(type, fileUrl,flag) {
				var that = this;
				uni.showLoading({
					title: '加载下载资源中'
				})
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						that.percent = 0;
						that.fileStatus = 'active'
						//请求视频真实地址
						uni.request({
							url: that.$reqUrl + '/lyz/getDownLoadFileUrl',
							method: "POST",
							timeout:35000,
							data: {
								link: fileUrl,
								type: type,
								source: that.$source,
								origin:flag
							},
							success: (res) => {
								if (res.data.code === '0001') {
									const downloadTask = uni.downloadFile({
										url: res.data.data, 
										success: (res) => {
											if (res.statusCode === 200) {
												if (type == 1) {
													uni.saveVideoToPhotosAlbum({
														filePath: res.tempFilePath
													});
													console.log("保存视频到相册")
												} else if (type == 2) {
													uni.saveImageToPhotosAlbum({
														filePath: res.tempFilePath
													})
													console.log("保存图片到相册")
												} 
											}else {
												uni.showModal({
													content:'资源无法访问，请联系作者反馈'
												})
											}
										},
										fail: function() {
											uni.showModal({
												content: '下载失败，请复制无水印链接到浏览器下载'
											})
										}
										});
										downloadTask.onProgressUpdate((res) => {
											that.percent = res.progress;
											if (res.progress == 100) {
												uni.showToast({
													icon: 'success',
													title: '文件已保存到相册'
												})
											}
										});
								} else {
									uni.showModal({
										content: '资源文件暂时无法下载 请复制无水印链接到浏览器下载 有疑问请联系微信 ' +
											getApp().globalData.author
									})
			
								}
							},
							complete() {
								uni.hideLoading()
							}
						});
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showModal({
							content: '您没有同意相册权限,视频无法保存[请点击小程序右上角设置按钮 开启相册权限]'
						})
					}
				})
			},
			targetMp4Download:function(type,downloadUrl) {
				var that = this;
				uni.showToast({
					title:'保存相册中',
					icon:'loading'
				})
				that.percent = 0;
				that.fileStatus = 'active'
				var randomStr = Math.random().toString(36).substr(2);
				var fileType = null;
				if(type == 1) {
					fileType = randomStr + ".mp4"
				}else {
					fileType = randomStr + ".png"
				}
				var newFilePath = wx.env.USER_DATA_PATH+'/' + fileType;
				const downloadTask = uni.downloadFile({
					url: downloadUrl, 
					filePath:newFilePath,
					success: (res) => {
						if (res.statusCode === 200) {
							if (type == 1) {
								uni.saveVideoToPhotosAlbum({
									filePath: newFilePath,
									success: function () {
										console.log('save success');
									},
									fail: (errRes) => {
										console.log('save error' + errRes);
									}
								});
								console.log("保存视频到相册")
							} else if (type == 2) {
								uni.saveImageToPhotosAlbum({
									filePath: newFilePath
								})
								console.log("保存图片到相册")
							} 
						}else {
							uni.showModal({
								content:'资源无法访问，请联系作者反馈'
							})
						}
					},
					fail: function() {
						uni.showModal({
							content: '下载失败，请复制无水印链接到浏览器下载'
						})
					}
					});
					downloadTask.onProgressUpdate((res) => {
						that.percent = res.progress;
						if (res.progress == 100) {
							uni.showToast({
								icon: 'success',
								title: '文件已保存到相册'
							})
						}
					});
			}
		}
	}
</script>

<style>	
	.container {
		width: 100%;
		padding-bottom: 30upx;
	}
	
	.video-play {
		width: 100%;
		height: 240px;
	}
	
	.tui-center {
		padding:15upx;
	}
	
	.save-btn {
		background-color: #4DABEB;
		color:white;
		
	}
	
	.tui-flex-box {
		padding: 10upx 10upx 10upx 10upx;
		font-size: 26upx;
	}
	
	.water-teach {
		text-align: center;
		margin-top: 10upx;
	}
	
	.tui-nickname {
		font-size: 30rpx;
		font-weight: 500;
		color: #13227a;
		display: flex;
		align-items: center;
		justify-content: center;
		text-decoration:underline
	}
	
	.tui-img-vip {
		width: 60rpx;
		height: 30rpx;
		margin-right: 18rpx;
	} 
	
	.prize-btn {
		width: 80%;
	}
	
	.ad-img {
		margin-top: 20upx;
		text-align: center;
	}
	
	.ad {
		justify-content: center;
	}
</style>
